package net.yebaihe.wc;

import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class Sessions extends StateMachine{

	private ListView lstSessions;
	private SQLiteDatabase listdb;

	class SessionSimpleCursorAdapter extends SimpleCursorAdapter{

		public SessionSimpleCursorAdapter(Context context, int layout,
				Cursor c, String[] from, int[] to) {
			super(context, layout, c, from, to);
		}
		
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);
			String title="未指定标题";
			if (cursor.getString(3)!=null){
				title=cursor.getString(3);
			}
			String date="未指定时间";
			if (cursor.getString(2)!=null){
				Date d=new Date(cursor.getLong(2));
				date=""+(d.getYear()+1900)+"年"+d.getMonth()+"月"+d.getDate()+"日";
			}
			TextView t=(TextView) view.findViewById(R.id.txttitle);
			TextView d=(TextView) view.findViewById(R.id.txtdate);
			t.setText(title);
			d.setText(date);
		}		
	}
	
	@Override
	protected String getTopbarTitle() {
		return "我的聚餐";
	}

	@Override
	protected void prepareClient(View client) {
		listdb=MyHelper.get(this).getReadableDatabase();
		lstSessions=(ListView)client.findViewById(R.id.lstSession);
		refreshLstSession();
	}

	protected void onDestroy() {
        super.onDestroy();
        listdb.close(); //断开和数据库的连接，释放相关资源
    }

	private void refreshLstSession() {
		if (listdb!=null){
			UserInfoData userinfo = MyHelper.get(this).getCurrUserInfoData(this.getWCAppContext().email);
			if (userinfo!=null){
				Cursor c=listdb.rawQuery("select * from sessions where state=2 and (_id in (select sessionid from sessionuser where uid="+
						userinfo._id+") or fromuid="+userinfo._id+")", null);
				startManagingCursor(c);
				ListAdapter listAdapter = new SessionSimpleCursorAdapter(this, R.layout.itemsession,
						c,
						new String[]{"title","timestamp"},
						new int[]{R.id.txttitle,R.id.txtdate});
				lstSessions.setAdapter(listAdapter);
				lstSessions.setOnItemClickListener(new OnItemClickListener(){
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						getWCAppContext().sessionid=(int) arg3;
						changeToActivity(ShowSessionDetail.class);
					}
				});
			}
		}
	}

	@Override
	protected int getLayoutRes() {
		return R.layout.sessions;
	}

}
